import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd/lib/select';
import { get, uniq } from 'lodash';
import classnames from 'classnames';
import Gridcelleditwrapper from '@/components/form/gridcelleditwrapper';
import { getGantPopupContainer } from '@/utils/utils';
import styles from './index.less';

export interface MaterialSelectProps extends SelectProps {
  wrapMode: 'noWrap' | 'excel' | 'excel-large';
  extraClassName: string;
}

// 接收excel复制值
const ExcelSelect = (props: MaterialSelectProps) => {
  const { style, autoFocus, disabled, onBlur, onChange, extraClassName, value: _value, ...restProps } = props;

  const [dataSource, setDataSource] = useState([]);
  const [value, setValue] = useState();
  const [selectFocus, setSelectFocus] = useState(false);
  const [loading, setLoading] = useState(false);

  const keywordsRef = useRef('');
  const lastFetchOrder = useRef(1);
  const selectRef = useRef();

  const focusRef = useRef(selectFocus);

  useEffect(() => {
    if (_value && typeof _value == 'string') {
      const val = _value.split(',');
      setValue(val);
      setDataSource(val);
    } else {
      setValue(_value);
      // setDataSource(_value)
    }
  }, [_value]);

  useEffect(() => {
    focusRef.current = selectFocus;
  }, [selectFocus]);

  const onPaste = (event: KeyboardEvent) => {
    if (focusRef.current) {
      const clipText = event.clipboardData.getData('Text');
      const trimStr = clipText.trim();
      const withLF = (str: string) => /[\r\n]+/g.test(str);
      if (!withLF(trimStr)) return;

      const rcSelect = selectRef.current.rcSelect;
      if (!rcSelect) return;
      const { state, fireChange, setInputValue } = rcSelect;
      const oldValue = get(state, 'value', []);
      const result = trimStr.replaceAll(/\r\n/g, ',').split(',');
      const newValue = uniq([...oldValue, ...result]);

      fireChange(newValue);
      setTimeout(() => {
        setInputValue('');
      }, 0);
    }
  };

  useEffect(() => {
    window.addEventListener('paste', onPaste);
    return () => {
      window.removeEventListener('paste', onPaste);
    };
  }, []);

  const onSelectBlur = () => {
    setDataSource([]);
    setSelectFocus(false);
    setLoading(false);
    keywordsRef.current = '';
    lastFetchOrder.current = 1;
  };

  const onValueChange = useCallback(
    (value: any, rows: any) => {
      if (JSON.stringify(value) == '[]') {
        onChange(undefined, rows);
      } else {
        let val = value;
        if (Array.isArray(value)) {
          val = value.join(',');
        }
        onChange(val, rows);
      }
    },
    [onChange],
  );

  const onInputKeyDown = useCallback((e: { key: string; target: { value: string } }) => {
    if (!e.target.value) return;
    if (e.key == 'Enter') {
      if (focusRef.current) {
        const rcSelect = selectRef.current.rcSelect;
        if (!rcSelect) return;
        const { state, fireChange, setInputValue } = rcSelect;
        const oldValue = get(state, 'value');
        const value = get(state, 'inputValue');
        const result = value.replaceAll(/\r\n/g, ',').split(',');
        const newValue = uniq([...oldValue, ...result]);
        fireChange(newValue);
        setTimeout(() => {
          setInputValue('');
        }, 0);
      }
    }
  }, []);

  return (
    <Gridcelleditwrapper onBlur={onBlur} visible={selectFocus} autoFocus={autoFocus}>
      <div className={classnames(extraClassName, styles.excelStyle)} style={{ width: '100%' }}>
        <Select
          ref={selectRef}
          size="small"
          mode="tags"
          allowClear
          tokenSeparators={[',', '，', '、', '/']}
          style={{ paddingTop: 2, ...style }}
          autoFocus={autoFocus}
          disabled={disabled}
          loading={loading}
          open={false}
          value={value}
          notFoundContent="输入搜索内容进行搜索"
          placeholder="逗号分隔支持多选"
          getPopupContainer={getGantPopupContainer}
          onBlur={onSelectBlur}
          onChange={onValueChange}
          onInputKeyDown={onInputKeyDown}
          onFocus={setSelectFocus.bind(null, true)}
          {...restProps}
        />
      </div>
    </Gridcelleditwrapper>
  );
};

export default ExcelSelect;
